package com.defysoft.waukids.slide;

import java.util.Calendar;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.R;


public class Slide_Field_Trip_A extends BaseActivity implements OnClickListener {
	String FK_Cla_Mem_Code,FK_Sch_Mem_Code,Sch_Name,Cla_Name;
	TextView textView[] = new TextView[1];
	ImageView imageView[] = new ImageView[2];
	Toolbar toolbar;
	private SharedPreferences fieldTrip;
	SharedPreferences.Editor editor;
	String push[] = new String[2];
	
	final int START_GCM = 1;
	final int END_GCM = 2;
	final int SUCCESS_STOP_GCM = 7;
	final int FAIL_STOP_GCM = 8;
	final int SUCCESS_START_GCM = 9;
	final int FAIL_START_GCM = 10;
	AlertDialog.Builder builder;
	AlertDialog alertDialog;
	//현장학습 초기화
	Calendar calendar;
	String date;
	String nowdate;	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.slide_fleld_trip_a);
		setStartData();
		setStartToolbar();
	}

	@Override
	public void setStartData() {
		super.setStartData();
		textView[0] = (TextView)findViewById(R.id.SLIDE_FIELD_TRIP_TV_MESSAGE); //상태정보출력용.
		imageView[0] = (ImageView)findViewById(R.id.SLIDE_FIELD_TRIP_TV_START); //현장학습 시작.
		imageView[1] = (ImageView)findViewById(R.id.SLIDE_FIELD_TRIP_TV_STOP); //현장학습종료.
		FK_Cla_Mem_Code = getIntent().getStringExtra("FK_Cla_Mem_Code");	//반코드.
		FK_Sch_Mem_Code = getIntent().getStringExtra("FK_Sch_Mem_Code");	//학원코드.
		Sch_Name = getIntent().getStringExtra("Sch_Name");					//학원이름.
		Cla_Name = getIntent().getStringExtra("Cla_Name");					//학원이름.
		fieldTrip = getSharedPreferences("fieldTrip", MODE_PRIVATE);
		editor = fieldTrip.edit();

		for (int i = 0; i < imageView.length; i++) {
			imageView[i].setOnClickListener(this);
		}
		toolbar = (Toolbar)findViewById(R.id.SLIDE_FIELD_TRIP_TOOL);
		setNow();	//현재 알림값으로 초기화.
		//현장학습 초기화
		findViewById(R.id.SLIDE_FIELD_TRIP_BTN_NEW).setOnClickListener(this);	//눌리면 초기화.
		calendar = Calendar.getInstance();	//하루지나면 초기화.
		date = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		nowdate = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		if (!fieldTrip.getString("date", "0").equals(nowdate)) {
			editor.clear();
			editor.commit();
			setNow();
		}
	}
	
	private void setNow() {	//현재 알림값으로 초기화.
		imageView[0].setVisibility(View.VISIBLE);
		imageView[1].setVisibility(View.VISIBLE);
		push[0] = fieldTrip.getString("fieldTrip_start", "0");
		push[1] = fieldTrip.getString("fieldTrip_stop", "0");
			if (push[0].equals("0")) {
				textView[0].setText("시작하려면 현장학습START를\n클릭하세요.");
				imageView[1].setVisibility(View.INVISIBLE);
			} else {
				textView[0].setText("현장학습 진행중 입니다.");
				imageView[0].setVisibility(View.INVISIBLE);
			}
	}

	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(SLIDE_FIELD_TRIP_BACK, new Intent().putExtra("fieldTripMessage", textView[0].getText().toString()));
				finish();
			}
		});
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SLIDE_FIELD_TRIP_TV_START:
			dialog_Delete(1);
			break;
		case R.id.SLIDE_FIELD_TRIP_TV_STOP:
			dialog_Delete(2);
			break;
		case R.id.SLIDE_FIELD_TRIP_BTN_NEW:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("현장학습을 초기화 하겠습니까?")
			.setCancelable(false)
			.setPositiveButton("네", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					editor.clear();
					editor.commit();
					setNow();
					dialog.cancel();
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			alertDialog = builder.create();
			alertDialog.show();
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case START_GCM:
					startGcmThread(1);
					break;
				case END_GCM:
					startGcmThread(2);
					
					break;

				}
			}
		});
		startDIal();
		firstThread.start();
	}

	protected void startGcmThread(int mode) {	//야외학습시작GCM보내기.
		try {
			JSONObject jsonObject;
			if (mode == 1) {	//현장학습시작.
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_FIELDTRIP_GCM, "FK_Cla_Mem_Code="+FK_Cla_Mem_Code+"&FK_Sch_Mem_Code="+FK_Sch_Mem_Code+"&Sch_Name="+Sch_Name+"&Cla_Name="+Cla_Name+"&mode=start"));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_START_GCM, "");
				} else {
					onNetworkCallback(FAIL_START_GCM, jsonObject.getString("message"));
				}
			} else {
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_FIELDTRIP_GCM, "FK_Cla_Mem_Code="+FK_Cla_Mem_Code+"&FK_Sch_Mem_Code="+FK_Sch_Mem_Code+"&Sch_Name="+Sch_Name+"&Cla_Name="+Cla_Name+"&mode=stop"));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_STOP_GCM, "");
				} else {
					onNetworkCallback(FAIL_STOP_GCM, jsonObject.getString("message"));
				}
			}
			

		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		};	
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case SUCCESS_START_GCM:		//현장학습 시작 GCM발송 완료. 여기에서 버튼변경.
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, "메세지 발송을 완료하였습니다.", Toast.LENGTH_SHORT).show();
			textView[0].setText("현장학습 진행중 입니다.");
			imageView[0].setVisibility(View.INVISIBLE);
			imageView[1].setVisibility(View.VISIBLE);
			editor.putString("fieldTrip_start", "1");
			editor.putString("fieldTrip_stop", "0");
			editor.putString("date", date);
			editor.commit();
			
			break;

		case SUCCESS_STOP_GCM:		//현장학습 종료 GCM발송 완료. 여기서 버튼 변경.
			endDIal();
			if (firstThread == null) {firstThread.interrupt();}
			textView[0].setText("시작하려면 현장학습START를\n클릭하세요.");
			Toast.makeText(this, "메세지 발송을 완료하였습니다.", Toast.LENGTH_SHORT).show();
			imageView[1].setVisibility(View.INVISIBLE);
			imageView[0].setVisibility(View.VISIBLE);
			editor.putString("fieldTrip_start", "0");
			editor.putString("fieldTrip_stop", "1");
			editor.commit();
			break;
			
		case FAIL_START_GCM:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case FAIL_STOP_GCM:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;

		}
	}


	private void dialog_Delete(int i) {
		builder = new AlertDialog.Builder(this);
		if (i==1) {	//현장학습 시작 클릭
			builder.setMessage("현장학습을 시작 하겠습니까?")
			.setCancelable(false)
			.setPositiveButton("네", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startNetwork(START_GCM);
					dialog.cancel();
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
		} else if(i==2){
			builder.setMessage("현장학습을 종료 하겠습니까?")
			.setCancelable(false)
			.setPositiveButton("네", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startNetwork(END_GCM);
					dialog.cancel();
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
		}
		alertDialog = builder.create();
		alertDialog.show();
	}
}//CLASS_END
